<?php
//this class is only useable in php 5.3 and above! (which i have)
//if its going to need the database then its probably smart to require it before we start
require_once(LIB_PATH.DS.'database.php');

class DatabaseObject
{
    protected static $table_name;
    
    public static function find_all()
    {        
        $sql="SELECT * FROM ".static::$table_name;
        $result_set=self::find_by_sql($sql);
        return $result_set;
    }
    
    public static function find_by_id($id=0)
    {
        global $database;
        $sql="SELECT * FROM ".static::$table_name." WHERE id={$id}";
        $result_array=static::find_by_sql($sql);
        return !empty($result_array)?array_shift($result_array):false;
    }
    
    public static function find_by_sql($sql="")
    {
        global $database;
        $result_set=$database->query($sql);
        $object_array=array();
        while($row=$database->fetch_array($result_set))
        {
            $object_array[]=static::instantiate($row);
        }
        return $object_array;
    }

    private static function instantiate($record)
    {
       $class_name= get_called_class();
       $object = new $class_name;
       // $object->id=$record['id'];
       // $object->username=$record['username'];
       // $object->password=$record['password'];
       // $object->firstname=$record['first_name'];
       // $object->lastname=$record['last_name'];
        
        foreach($record as $attribute=>$value)
        {
            if($object->has_attribute($attribute))
            {
                $object->$attribute=$value;
            }
        }
        
        return $object;
    }
    
    private function has_attribute($attribute)
    {
        //get_object_vars returns an associative array with all attributes including private ones!
        //as the keys and their current values as the value
        $object_vars = get_object_vars($this);
        //we dont care about the value we just want to know if the key exists
        //will return true or false
        return array_key_exists($attribute, $object_vars);
    }
}
?>
